<?php

/**
 * This file is part of Webman AI.
 *
 * @author    walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link      http://www.workerman.net/
 */

namespace plugin\ai\app\controller;

use plugin\ai\app\model\AiImage;
use support\Response;
use Workerman\Protocols\Http\Request;

class GalleryController extends Base
{
    /**
     * 不需要登录的方法
     *
     * @var string[]
     */
    protected $noNeedLogin = ['index', 'images'];

    /**
     * @param Request $request
     * @return Response
     */
    public function index(Request $request): Response
    {
        return view('gallery/index');
    }

    /**
     * 获取图片
     * @param Request $request
     * @return Response
     */
    public function images(Request $request): Response
    {
        $id = $request->get('id', 2147483647);
        $limit = $request->get('limit', 20);
        $limit = min($limit, 200);
        $images = AiImage::with('user')->select(['id', 'prompt', 'thumb_url', 'user_id', 'image_url', 'created_at', 'image'])
            ->where('id', '<', $id)->where('gallery', 1)
            ->whereNotNull('thumb_url')->orderBy('id', 'desc')->limit($limit)->get();
        foreach ($images as &$image) {
            $image->image = json_decode($image->image, true);
        }

        return $this->json(0, 'ok', ['items' => $images]);
    }

}